import Adapter from "../core/Adapter";
import Util from "../core/Util";

class WxArg{
    withShareTicket: boolean;
    success(){};
    fail(){};
    complete(){};
}
export default class AdapterWx extends Adapter {
    videoAd: any;
    videAdLoaded: boolean;
    handderVideo: any;
    bannerTj: any;
    portalTj: any;
    interstitialAd: any;
    bannerAd: any;
    userInfo: any;
    loginCallback: Laya.Handler;
    
    constructor() {
        super();
        this.name = 'wx';
        let arg = new WxArg();
        arg.withShareTicket = true;
        wx.showShareMenu(arg);
        wx.onShareAppMessage(function () {
            return {
                title: '看看这关你能不能过',
                imageUrlId: 'FpfFbemWQBG2+dk8o8cnpg==',
                imageUrl: "https://mmocgame.qpic.cn/wechatgame/YKyTWcZtFxyTUZclQUWNc1c76J2uD4yh3x4E4K4C6MkHQIK8WsJOwicvf6xK3PJDn/0"
            }
        })
    }

    autoLogin():void{
        let that = this;
        wx.login({
            success(res) {
                if (res.code) {
                    Util.postData("game/wxapi/login",{code: res.code}).then(data=>{
                        that.uid = data.uid;
                    });
                } else {
                    console.log('登录失败！' + res['errMsg']);
                }
            }
        });
    }

    init() {
        let OpenDataContext = wx.getOpenDataContext();
        OpenDataContext.postMessage({
            type: 0,
            w: Laya.stage.designWidth,
            h: Laya.stage.designHeight
        });

        // 创建激励视频广告实例，提前初始化
        this.videoAd = wx.createRewardedVideoAd({
            adUnitId: 'adunit-86c88e0f42c7e54c'
        });

        this.videoAd.onLoad(() => {
            this.videAdLoaded = true;
            console.log('激励视频 广告加载成功');

        });

        this.videoAd.onError(err => {
            console.log(err);
            this.videAdLoaded = false;
        });
        this.videoAd.onClose(res => {
            // 用户点击了【关闭广告】按钮
            // 小于 2.1.0 的基础库版本，res 是一个 undefined
            if (res && res.isEnded || res === undefined) {
                this.handderVideo && this.handderVideo.run();
            } else {
                // 播放中途退出，不下发游戏奖励
            }
        });
        // 创建推荐位实例，提前初始化
        if (wx['createGameBanner']) {
            this.bannerTj = wx['createGameBanner']({
                adUnitId: 'PBgAAgU0H8fGufQ4',
                style: {
                    left: 0,
                    top: Laya.Browser.clientHeight - 130
                }
            });
            this.bannerTj.onError(
                err => {
                    console.log(err);
                }
            );
            this.bannerTj.onLoad(() => {
                console.log("推荐组件加载成功");
            });
        }



        // 创建推荐位实例，提前初始化
        if (wx['createGamePortal']) {
            this.portalTj = wx['createGamePortal']({
                adUnitId: 'PBgAAgU0H8fKh1zM'
            });
            this.portalTj.onError(
                err => {
                    console.log(err);
                }
            );
            this.portalTj.onLoad(() => {
                console.log("推荐组件加载成功");
            });
        }


        return true;
    }

    showBannerTj() {
        // 定义推荐位
        let bannerTj = this.bannerTj;

        // 在适合的场景显示推荐位
        // err.errCode返回1004时表示当前没有适合推荐的内容，建议游戏做兼容，在返回该错误码时展示其他内容
        if (bannerTj) {
            bannerTj.show().catch((err) => {
                console.error(err)
            });
        }
        return true;
    }

    hideBannerTj() {
        let bannerTj = this.bannerTj;
        if (bannerTj) {
            bannerTj.hide();
        }
    }

    showPortalTj() {
        // 在适合的场景显示推荐位
        // err.errCode返回1004时表示当前没有适合推荐的内容，建议游戏做兼容，在返回该错误码时展示其他内容
        if (this.portalTj) {
            let portalTj = this.portalTj;
            portalTj.load().then(() => {
                portalTj.show()
            }).catch((err) => {
                console.error(err)
            });
            return true;
        }
    }


    hasVidoAd() {
        return this.videoAd && this.videAdLoaded;
    }



    showVideoAd(handler) {
        if (!this.videoAd) {
            return;
        }
        this.handderVideo = handler;
        var videoAd = this.videoAd;
        // 用户触发广告后，显示激励视频广告
        videoAd.show().catch(() => {
            // 失败重试
            videoAd.load()
                .then(() => videoAd.show())
                .catch(err => {
                    console.log('激励视频 广告显示失败')
                })
        });
        return true;

    }

    showInsertAd() {

        // 定义插屏广告


        // 创建插屏广告实例，提前初始化
        if (!this.interstitialAd) {
            this.interstitialAd = wx['createInterstitialAd']({
                adUnitId: 'adunit-5ac610a284d5674b'
            });
        }

        let interstitialAd = this.interstitialAd;
        // 在适合的场景显示插屏广告
        if (interstitialAd) {
            interstitialAd.show().catch((err) => {
                console.error(err)
            });
            return true;
        }
    }

    showBannerAd(left, top, width) {
        // 创建 Banner 广告实例，提前初始化
        if (!this.bannerAd) {
            this.bannerAd = wx.createBannerAd({
                adUnitId: 'adunit-7aff42599bc294c3',
                adIntervals: 30,
                style: {
                    left: left,
                    top: top,
                    width: width,
                    height:100
                }
            });
            this.bannerAd.onError(err => {
                console.log(err);
            });
            this.bannerAd.onLoad(() => {
                console.log('banner 广告加载成功');
            });
        }
        let bannerAd = this.bannerAd;
        bannerAd.style.left = left;
        bannerAd.style.top = top;
        bannerAd.style.width = width;

        // 在适合的场景显示 Banner 广告
        bannerAd.show().then(() => console.log('banner 广告显示')).catch(err => console.log(err));
        return true;
    }


    hideBannerAd() {
        if (this.bannerAd) {
            this.bannerAd.hide();
        }
    }
    save(data) {
        let OpenDataContext = wx.getOpenDataContext();
        OpenDataContext.postMessage({
            type: 3,
            data: data
        });
        return true;
    }

    getFriends(data):boolean {
        let OpenDataContext = wx.getOpenDataContext();
        OpenDataContext.postMessage({
            type: 1,
            level: data
        });
        return true;
    }

    showNormalToprank(y = 0) {
        let OpenDataContext = wx.getOpenDataContext();
        OpenDataContext.postMessage({
            type: 6,
            y: y
        });
    }

    showPopupToprank(y = 0) {
        let OpenDataContext = wx.getOpenDataContext();
        OpenDataContext.postMessage({
            type: 7,
            y: y
        });
    }

    /**
     * 按10个等级归为1组的数据保存
     */
    saveLvlData(level, lvlData) {
        let OpenDataContext = wx.getOpenDataContext();
        OpenDataContext.postMessage({
            type: 4,
            data: lvlData,
            level: level
        });
        return true;
    }


    loadLvlData(level) {
        let OpenDataContext = wx.getOpenDataContext();
        OpenDataContext.postMessage({
            type: 5,
            level: level
        });
        return true;
    }

    freshMyScore(score) {
        let OpenDataContext = wx.getOpenDataContext();
        OpenDataContext.postMessage({
            type: 2,
            score: score
        });
    }

    share() {
        wx.shareAppMessage({
            title: '看看这关你能不能过',
            imageUrlId: 'FpfFbemWQBG2+dk8o8cnpg==',
            imageUrl: "https://mmocgame.qpic.cn/wechatgame/YKyTWcZtFxyTUZclQUWNc1c76J2uD4yh3x4E4K4C6MkHQIK8WsJOwicvf6xK3PJDn/0"
        });
    }

    getApiUrl(action){
        return 'http://lc169.yeyeyoo.com/game/wxapi/'+action;
    }

    postUserData(){
        if(this.userInfo && this.uid){
            this.userInfo.openid = this.uid;
            wx.request(
                {
                    url:this.getApiUrl('userinfo'),
                    method:'POST',
                    data:this.userInfo,
                    success:function(res){
                        console.log(res.data);
                    }
                }
            );
            //清理临时数据
            delete this.uid;
            delete this.userInfo;
        }else{
            console.log(this.uid);
            console.log(this.userInfo);
        }
    }

    login(callback) {
        var that = this;        
        this.loginCallback = callback;
        wx.getSetting({
            success: (res) => {
                const authSetting = res.authSetting
                if (authSetting['scope.userInfo'] === true) {
                    wx.getUserInfo({
                        success: (res) => {
                            
                            that.userInfo = res.userInfo;
                            that.postUserData();
                            //用户已授权，可以直接调用相关 API
                            that.loginCallback && that.loginCallback.runWith(that.userInfo);
                        }
                    });
                } else if (authSetting['scope.userInfo'] === false) {
                    // 用户已拒绝授权，再调用相关 API 或者 wx.authorize 会失败，需要引导用户到设置页面打开授权开关
                    that.addLoginBtn();
                } else {
                    // 未询问过用户授权，调用相关 API 或者 wx.authorize 会弹窗询问用户
                    that.addLoginBtn();
                }
            }
        });
    }

    addLoginBtn() {
        const width = 90;
        const height = 35;

        const button = wx.createUserInfoButton({
            type: 'image',
            image: 'images/start.png',
            style: {
                left: window.innerWidth / 2 - width / 2,
                top: window.innerHeight / 2 - height / 2,
                width,
                height,
            }
            
        });
        let that  = this;
        button.onTap((res) => {
            if (res.rawData) {
                button.destroy();
                try {
                    let info = JSON.parse(res.rawData);
                    that.userInfo = info;
                    that.postUserData();
                    that.loginCallback && that.loginCallback.runWith(info);
                } catch (e) {
                    console.log(e, res);
                    that.loginCallback && that.loginCallback.runWith({"nickName":"请登录"});
                }
            } else {
                wx.showToast({
                    title: '请授权开始游戏',
                    icon: 'none',
                    duration: 1500
                })
            }
        });
    }

    loadSubRes(list,handler){
        const next = function(){
            var sub = list.pop();
            if(sub){
                const loadTask = wx.loadSubpackage({
                    name: sub, // name 可以填 name 或者 root
                    success: function() {
                        next();
                    },
                    fail: function() {
                        console.log("分包加载失败:"+sub);
                    },complete:function(){}
                  });
                  
                  loadTask.onProgressUpdate(res => {
                    console.log('下载进度', res.progress)
                    console.log('已经下载的数据长度', res.totalBytesWritten)
                    console.log('预期需要下载的数据总长度', res.totalBytesExpectedToWrite)
                  });
            }else{
                handler.run();
            }
        }
        next();
    }

}